import {serialize} from "@/middleware/socket/fastJson";
import {UserService} from "@/middleware/db/userService";

let currentSocket = ''
let setIntervalWebSocketPush = null


export const createSocket = url => {
    currentSocket && currentSocket.close()
    if (!currentSocket) {
        console.log('建立websocket连接')
        currentSocket = new WebSocket(url)
        currentSocket.onopen = onOpenWebSocket
        currentSocket.onmessage = onMessageWebSocket
        currentSocket.onerror = onErrorWebSocket
        currentSocket.onclose = onCloseWebSocket
    } else {
        console.log('websocket已连接')
    }
}

const onOpenWebSocket = async () => {
    console.log('打开socket');
    await sendAuth();
}

async function sendAuth() {
    const currentUser = await UserService.getCurrentUser();
    console.log('current id ' + currentUser.id);
    const message = {
        uid: currentUser.id,
        tk: ''
    };
    currentSocket.send(serialize('AUTH', message));
    console.log('发送 auth');
}

const onErrorWebSocket = () => {
    currentSocket.close()
    clearInterval(setIntervalWebSocketPush)
    console.log('连接失败重连中')
    if (currentSocket.readyState !== 3) {
        currentSocket = null
        createSocket()
    }
}


const onMessageWebSocket = e => {
    console.log('peter socket receive ' + e.data);
    window.dispatchEvent(new CustomEvent('onMessageWebSocket', {
        detail: {
            data: e.data
        }
    }))
}

const onConnecting = message => {
    setTimeout(() => {
        if (currentSocket.readyState === 0) {
            onConnecting(message)
        } else {
            currentSocket.send(JSON.stringify(message))
        }
    }, 1000)
}

export const sendMessageWebSocket = message => {
    console.log('发消息' + message);
    if (currentSocket !== null && currentSocket.readyState === 3) {
        currentSocket.close()
        createSocket()
    } else if (currentSocket.readyState === 1) {
        currentSocket.send(message)
    } else if (currentSocket.readyState === 0) {
        onConnecting(message)
    }
}

const onCloseWebSocket = () => {
    clearInterval(setIntervalWebSocketPush)
    console.log('websocket已断开....正在尝试重连')
    if (currentSocket.readyState !== 2) {
        currentSocket = null
        createSocket('ws://192.168.0.43:30099')
    }
}

export const sendPing = (time = 5000, ping = 'P') => {
    clearInterval(setIntervalWebSocketPush)
    currentSocket.send(ping)
    console.log('发送 ping');
    setIntervalWebSocketPush = setInterval(() => {
        currentSocket.send(ping)
    }, time)
}